package org.codeart.singleton;

/**
 * 懒汉式，线程安全
 * 使用双重校验锁来保证线程安全
 */
public class Singleton04 {

    // 使用volatile保证变量的可见性，还可以屏蔽指令重排序
    private static volatile Singleton04 instance;

    private Singleton04() {

    }

    public static Singleton04 getInstance() {
        if (instance == null) {
            synchronized (Singleton04.class) {
                // 第二次判断，抢到锁之后再次进行判断是否为null
                if (instance == null) {
                    instance = new Singleton04();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                Singleton04 s = getInstance();
                System.out.println(Thread.currentThread().getName() + ": " + s);
            }).start();
        }
    }
}
